//
//  DR_FileModel.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/14.
//

import UIKit
import PDFKit

// MARK: - 文件类型枚举
enum DR_FileType: String {
    case pdf = "PDF"
    case word = "Word"
    case excel = "Excel"
    case ppt = "PPT"
    
    var iconName: String {
        switch self {
        case .pdf:
            return "home_pdf"
        case .word:
            return "home_word"
        case .excel:
            return "home_excel"
        case .ppt:
            return "home_ppt"
        }
    }
    
    static func from(fileExtension: String) -> DR_FileType? {
        let ext = fileExtension.lowercased()
        switch ext {
        case "pdf":
            return .pdf
        case "doc", "docx":
            return .word
        case "xls", "xlsx":
            return .excel
        case "ppt", "pptx":
            return .ppt
        default:
            return nil
        }
    }
}

// MARK: - 通用文件模型
struct DR_FileModel {
    let fileName: String
    let fileURL: URL
    let fileSize: Int64
    let createDate: Date
    let fileType: DR_FileType
    let pageCount: Int // PDF 有页数，其他文件类型为 0
    
    var displayName: String {
        let ext = fileURL.pathExtension
        return fileName.replacingOccurrences(of: ".\(ext)", with: "")
    }
    
    var fileSizeString: String {
        return formatFileSize(fileSize)
    }
    
    private func formatFileSize(_ bytes: Int64) -> String {
        let formatter = ByteCountFormatter()
        formatter.allowedUnits = [.useKB, .useMB]
        formatter.countStyle = .file
        return formatter.string(fromByteCount: bytes)
    }
    
    // 从 DR_PDFFileModel 转换
    init(from pdfModel: DR_PDFFileModel) {
        self.fileName = pdfModel.fileName
        self.fileURL = pdfModel.fileURL
        self.fileSize = pdfModel.fileSize
        self.createDate = pdfModel.createDate
        self.fileType = .pdf
        self.pageCount = pdfModel.pageCount
    }
    
    // 从文件 URL 创建
    init(fileURL: URL) {
        self.fileURL = fileURL
        self.fileName = fileURL.lastPathComponent
        
        // 获取文件属性
        let attributes = (try? FileManager.default.attributesOfItem(atPath: fileURL.path)) ?? [:]
        self.fileSize = (attributes[.size] as? Int64) ?? 0
        self.createDate = (attributes[.creationDate] as? Date) ?? Date()
        
        // 确定文件类型
        let fileExtension = fileURL.pathExtension.lowercased()
        self.fileType = DR_FileType.from(fileExtension: fileExtension) ?? .pdf
        
        // 如果是 PDF，获取页数
        if self.fileType == .pdf {
            if let pdfDocument = PDFDocument(url: fileURL) {
                self.pageCount = pdfDocument.pageCount
            } else {
                self.pageCount = 0
            }
        } else {
            self.pageCount = 0
        }
    }
}

